//package com.itheima.backend.controller;
//
//import com.itheima.backend.pojo.Message;
//import com.itheima.backend.service.JIEKOU.MessageService;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.List;
//
//@RestController
//@RequestMapping("/messages")
//public class MessageController {
//
//    private final MessageService messageService;
//
//    public MessageController(MessageService messageService) {
//        this.messageService = messageService;
//    }
//
//    // 发布留言
//    @PostMapping
//    public String createMessage(@RequestBody Message message) {
//
//        messageService.createMessage(message);
//        return "Message created successfully!";
//    }
//
//    // 删除留言
//    @DeleteMapping("/{id}")
//    public String deleteMessage(@PathVariable Integer id) {
//        messageService.deleteMessageById(id);
//        return "Message deleted successfully!";
//    }
//
//    // 分页查询留言
//    @GetMapping
//    public List<Message> getMessages(@RequestParam int page, @RequestParam int size) {
//        return messageService.getMessages(page, size);
//    }
//
//    // 模糊查询留言
//    @GetMapping("/search")
//    public List<Message> searchMessages(
//            @RequestParam(required = false) String keyword,
//            @RequestParam(required = false) Integer userId) {
//
//        return messageService.searchMessages(keyword, userId);
//    }
//}
//package com.itheima.backend.controller;
//
//import com.itheima.backend.pojo.Message;
//import com.itheima.backend.service.JIEKOU.MessageService;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import java.util.List;
//
//@RestController
//@RequestMapping("/messages")
//public class MessageController {
//
//    private final MessageService messageService;
//
//    public MessageController(MessageService messageService) {
//        this.messageService = messageService;
//    }
//
//    // 发布留言（绑定用户信息）
//    @PostMapping
//    public String createMessage(@RequestBody Message message, @RequestAttribute("userId") Integer userId) {
//        if (userId == null) {
//            throw new RuntimeException("Unauthorized: Missing user information");
//        }
//
//        // 将用户 ID 绑定到留言
//        message.setUserId(userId);
//        messageService.createMessage(message);
//        return "Message created successfully!";
//    }
//
//    // 删除留言（仅限留言所有者）
//    @DeleteMapping("/{id}")
//    public String deleteMessage(@PathVariable Integer id, @RequestAttribute("userId") Integer userId) {
//        if (userId == null) {
//            throw new RuntimeException("Unauthorized: Missing user information");
//        }
//
//        // 检查留言所有者
//        Message message = messageService.getMessageById(id);
//        if (message == null || !message.getUserId().equals(userId)) {
//            throw new RuntimeException("Unauthorized: You can only delete your own messages");
//        }
//
//        messageService.deleteMessageById(id);
//        return "Message deleted successfully!";
//    }
//
//    // 分页查询留言（查询当前用户的留言，管理员可以查询所有）
//    @GetMapping
//    public List<Message> getMessages(@RequestParam int page, @RequestParam int size, @RequestAttribute("userId") Integer userId) {
//        // 可选：管理员逻辑（根据实际情况调整）
//        boolean isAdmin = false; // 根据实际情况调整
//        if (isAdmin) {
//            return messageService.getMessages(page, size); // 查询所有留言
//        } else {
//            return messageService.getMessagesByUserId(userId, page, size); // 查询当前用户的留言
//        }
//    }
//
//    // 模糊查询留言（默认查询自己的留言）
//    @GetMapping("/search")
//    public List<Message> searchMessages(
//            @RequestParam(required = false) String keyword,
//            @RequestParam(required = false) Integer userId,
//            @RequestAttribute("userId") Integer currentUserId) {
//
//        if (userId == null) {
//            userId = currentUserId; // 默认查询自己的留言
//        }
//
//        return messageService.searchMessages(keyword, userId);
//    }
//}


///real
//package com.itheima.backend.controller;
//
//import com.itheima.backend.pojo.Message;
//import com.itheima.backend.service.JIEKOU.MessageService;
//import com.itheima.backend.service.MessageServiceImpl;
//import com.itheima.backend.utils.JwtUtil;
//import jakarta.servlet.http.HttpServletRequest;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@RestController
//@RequestMapping("/messages")
//public class MessageController {
//
//    @Autowired
//    private MessageService messageService;
//
//    @Autowired
//    private MessageServiceImpl messageServiceImpl;
//
//    // 发布留言（需要登录）
//    @PostMapping
//    public Map<String, Object> createMessage(@RequestBody Message message, HttpServletRequest request) {
//        // 从请求中获取解析后的用户名或用户ID
//        Integer userId = (Integer) request.getAttribute("userId");
//        Map<String, Object> response = new HashMap<>();
//
//        if (userId == null) {
//            response.put("message", "Unauthorized: Missing user information");
//            return response;
//        }
//
//        // 将用户 ID 绑定到留言
//        message.setUserId(userId);
//        messageServiceImpl.createMessage(message);
//
//        response.put("message", "Message created successfully!");
//        return response;
//    }
//
//    // 删除留言（仅限留言所有者，且需要登录）
//    @DeleteMapping("/{id}")
//    public Map<String, Object> deleteMessage(@PathVariable Integer id, HttpServletRequest request) {
//        Integer userId = (Integer) request.getAttribute("userId");
//        Map<String, Object> response = new HashMap<>();
//
//        if (userId == null) {
//            response.put("message", "Unauthorized: Missing user information");
//            return response;
//        }
//
//        // 检查留言是否存在并且是否是当前用户的留言
//        Message message = messageServiceImpl.getMessageById(id);
//        if (message == null) {
//            response.put("message", "Message not found");
//            return response;
//        }
//
//        if (!message.getUserId().equals(userId)) {
//            response.put("message", "Unauthorized: You can only delete your own messages");
//            return response;
//        }
//
//        messageServiceImpl.deleteMessageById(id);
//        response.put("message", "Message deleted successfully!");
//        return response;
//    }
//
////    // 查询所有留言（管理员可以查询所有，普通用户只能查询自己的留言）
////    @GetMapping
////    public List<Message> getAllMessages(HttpServletRequest request) {
////        Integer userId = (Integer) request.getAttribute("userId");
////        System.out.println("Current user ID: " + userId);  // 可选：记录访问日志
////        boolean isAdmin = false; // 可通过某些业务逻辑来判断是否为管理员
////
////        if (isAdmin) {
////            return messageServiceImpl.getMessages(); // 查询所有留言
////        } else {
////            return messageServiceImpl.getMessagesByUserId(userId); // 查询当前用户的留言
////        }
////    }
//
//    // 根据 ID 查询留言（需要登录）
//    @GetMapping("/{id}")
//    public Map<String, Object> getMessageById(@PathVariable Integer id, HttpServletRequest request) {
//        Integer userId = (Integer) request.getAttribute("userId");
//        Map<String, Object> response = new HashMap<>();
//
//        if (userId == null) {
//            response.put("message", "Unauthorized: Missing user information");
//            return response;
//        }
//
//        Message message = messageServiceImpl.getMessageById(id);
//        if (message == null) {
//            response.put("message", "Message not found");
//            return response;
//        }
//
//        response.put("message", message);
//        return response;
//    }
//
//    // 模糊查询留言（默认查询当前用户的留言）
//    @GetMapping("/search")
//    public List<Message> searchMessages(@RequestParam(required = false) String keyword,
//                                        HttpServletRequest request) {
//        Integer userId = (Integer) request.getAttribute("userId");
//        System.out.println("Current user ID: " + userId); // 可选：记录访问日志
//
//        if (userId == null) {
//            throw new RuntimeException("Unauthorized: Missing user information");
//        }
//
//        return messageServiceImpl.searchMessages(keyword, userId); // 默认查询用户的留言
//    }
//}
//


package com.itheima.backend.controller;

import com.itheima.backend.pojo.Message;
import com.itheima.backend.service.JIEKOU.MessageService;
import com.itheima.backend.service.MessageServiceImpl;
import com.itheima.backend.service.UserServiceImpl;
import com.itheima.backend.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageServiceImpl messageServiceImpl;
    @Autowired
    private UserServiceImpl userServiceImpl;

    // 发布留言（需要登录）

    @PostMapping
    public Map<String, Object> createMessage(@RequestBody Message message, HttpServletRequest request) {
        // 从请求中获取解析后的用户名
        String username = (String) request.getAttribute("username");
        Map<String, Object> response = new HashMap<>();

        if (username == null) {
            response.put("message", "Unauthorized: Missing user information");
            return response;
        }
        //根据用户名来找到对应的用户ID
        int postuserid=userServiceImpl.getUserIdByUsername(username);
        // 将用户名绑定到留言（假设你的 Message 类有一个 setUsername 方法）
        message.setUsername(username);
        message.setUserId(postuserid);
        messageServiceImpl.createMessage(message);

        response.put("message", "Message created successfully!");
        return response;
    }

    // 删除留言（仅限留言所有者，且需要登录）
    //用户可以删除只属于自己的留言
    //管理员可以删除所有留言

    @DeleteMapping("/{id}")
    public Map<String, Object> deleteMessage(@PathVariable Integer id, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        Map<String, Object> response = new HashMap<>();

        if (username == null) {
            response.put("message", "Unauthorized: Missing user information");
            return response;
        }
        // 检查留言是否存在并且是否是当前用户的留言
        Message message = messageServiceImpl.getMessageById(id);
        if (message == null) {
            response.put("message", "没找到该留言");
            return response;
        }
        if(username.equals("nagisa")){
            messageServiceImpl.deleteMessageById(id);
            response.put("message", "Message deleted successfully!");
            return response;
        }


        if (!message.getUsername().equals(username)) {
            response.put("message", "无权限");
            return response;
        }

        messageServiceImpl.deleteMessageById(id);
        response.put("message", "Message deleted successfully!");
        return response;
    }

    // 查询留言（需要登录）
    //注意这里的id竟然是留言的编号，操他妈了

    @GetMapping("/{id}")
    public Map<String, Object> getMessageById(@PathVariable Integer id, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        Map<String, Object> response = new HashMap<>();

        if (username == null) {
            response.put("message", "Unauthorized: Missing user information");
            return response;
        }

        Message message = messageServiceImpl.getMessageById(id);
        if (message == null) {
            response.put("message", "Message not found");
            return response;
        }

        response.put("message", message);
        return response;
    }

    // 模糊查询留言（默认查询当前用户的留言）

//    @GetMapping("/search")
//    public List<Message> searchMessages(@RequestParam(required = false) String keyword,
//                                        HttpServletRequest request) {
//        String username = (String) request.getAttribute("username");
//        System.out.println("Current user: " + username); // 可选：记录访问日志
//
//        if (username == null) {
//            throw new RuntimeException("Unauthorized: Missing user information");
//        }
//
//        return messageServiceImpl.searchMessages(keyword, username); // 默认查询用户的留言
//    }
@GetMapping("/search")
public List<Message> searchMessages(@RequestParam(required = false) String keyword,
                                    @RequestParam(defaultValue = "1") int page,
                                    HttpServletRequest request) {
    String username = (String) request.getAttribute("username");
    System.out.println("Current user: " + username); // 可选：记录访问日志
    if (username == null) {
        throw new RuntimeException("Unauthorized: Missing user information");
    }

    // 调用 Service 层，传递分页参数
    return messageServiceImpl.searchMessages(keyword, username, page);
}



    @GetMapping("/searchall")
    public List<Message> searchAllMessages(@RequestParam(required = false) String keyword,
                                           @RequestParam(defaultValue = "1") int page,
                                           HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        System.out.println("Current user: " + username); // 可选：记录访问日志
        if (username == null) {
            throw new RuntimeException("Unauthorized: Missing user information");
        }
        return messageServiceImpl.searchAllmessages(keyword,page);
    }

    //需要改进
    @GetMapping("/allmessages")
    public List<Message> getAllMessages(@RequestParam(required = false) int page) {

        return messageServiceImpl.getMessages(page,5);
    }
}

